﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.Handlers;
using Tracy.DataModel;
using SharedLib;

namespace Tracy.Plugins.DownloadAdapters
{
    public class ThunderNewBTTaskDialogHandler : TaskMessageHandler
    {
        const int MAX_RETRY_TIMES_NEW_TASK_DIALOG = 120; //60 sec timeout

        private static object _lockHelper = new object();
        private static bool _autoStartSupported = true;

        private int SendKeyToThunderDialog(int dialoghWnd, int key)
        {

            List<IntPtr> childWindows = Win32Helper.GetChildWindows(new IntPtr(dialoghWnd));

            if (childWindows.Count == 1) //Thunder 7
            {
                int firstChild = childWindows[0].ToInt32();
                Win32Helper.PostMessage(firstChild, Win32Helper.WM_KEYDOWN, key, 0);
                return firstChild;
            }
            else
            {
                _autoStartSupported = false;
                throw new Exception("Unsupported new task dialog");
            }
            //return 0;
        }

        protected override void ProcessMessage(Messages.TaskMessage msg)
        {
            lock (_lockHelper)
            {
                if (msg != null && msg.Data != null && msg.Data is Resource && _autoStartSupported)
                {
                    Resource res = msg.Data as Resource;

                    string thunderDialogTitle = "新建BT任务";
                    string thunderDupDialogTitle = "MessageBox";
                    string thunderExistDialogTitle = "RepeatBtFileNameDlg";
                    int dialoghWnd = 0;
                    int retry = 0;
                    do
                    {
                        System.Threading.Thread.Sleep(500);
                        dialoghWnd = Win32Helper.FindWindow("#32770", thunderDialogTitle);
                        retry++;
                        if (retry >= MAX_RETRY_TIMES_NEW_TASK_DIALOG) throw new Exception("Failed to auto start Thunder BT task: Cannot find\"" + thunderDialogTitle + "\" Dialog"); //timeout
                    } while (dialoghWnd == 0 && !msg.CancelFlag);

                    //Send Enter key
                    int child = SendKeyToThunderDialog(dialoghWnd, Win32Helper.VK_RETURN);

                    //Wait for dialog to close

                    System.Threading.Thread.Sleep(1000);
                    if (Win32Helper.IsWindowVisible(dialoghWnd)) //dialog not closed
                    {
                        int dupFoundDialog = Win32Helper.FindWindow("#32770", thunderDupDialogTitle);
                        if (dupFoundDialog != 0) // Found dupliated task dialog
                        {
                            SendKeyToThunderDialog(dupFoundDialog, Win32Helper.VK_ESCAPE);
                            System.Threading.Thread.Sleep(1000);//Wait for dialog closing
                            throw new Exception("Failed to auto start Thunder BT task: Duplicated task found - " + res.Url);
                        }
                            
                        int existFoundDialog = Win32Helper.FindWindow("#32770", thunderExistDialogTitle);
                        if (existFoundDialog != 0) // Found "File already exists" dialog
                        {
                            SendKeyToThunderDialog(existFoundDialog, Win32Helper.VK_ESCAPE);
                            Win32Helper.PostMessage(child, Win32Helper.WM_KEYDOWN, Win32Helper.VK_ESCAPE, 0);//cancel original thunder BT task
                            System.Threading.Thread.Sleep(1000);//Wait for dialog closing
                            throw new Exception("Failed to auto start Thunder BT task: File already exists - " + res.Url);
                        }

                        //try close again
                        System.Threading.Thread.Sleep(1000);
                        Win32Helper.PostMessage(child, Win32Helper.WM_KEYDOWN, Win32Helper.VK_RETURN, 0);
                        if (Win32Helper.IsWindowVisible(dialoghWnd)) throw new Exception("Failed to auto start Thunder BT task: Cannot close\"" + thunderDialogTitle + "\" Dialog"); //timeout
                    }

                }
            }
        }
    }
}
